#! /bin/sh

if [ ! \( -f .git/config -a -f Makefile.mk.in \) ] ; then
	echo "${0} must be executed from project root directory."
	exit 1
fi

if [ ${#} -ne 1 ] ; then
	echo "Changelog path is a requred parameter."
	exit 1
fi

changelogFile="${1}"
codename=$(lsb_release -sc | tr A-Z a-z)
project=$(awk -F '= ' '/^PRJNAME.*=/{print $2}' Makefile.mk.in)

if [ -f "${changelogFile}" ] ; then
	echo "Changelog file already exits"
	exit 1
fi

git_get_author() {
	local ref="${1}"
	git log --no-color -n 1 --pretty=format:"%an" "${ref}"
}

git_get_date() {
	local ref="${1}"
	git log --no-color -n 1 --pretty=format:"%aD" "${ref}"
}

git_get_email() {
	local ref="${1}"
	git log --no-color -n 1 --pretty=format:"%ae" "${ref}"
}

git_get_body_from_tag() {
	local tag="${1}"
	git tag -n100 -l ${tag} | tail -n+3 | sed -e 's/^    /  /'
}

gen_changelog_entry() {
	if [ -f "${changelogFile}" ] ; then
		mv -f "${changelogFile}" "${changelogFile}.tmp"
	fi
	local tag="${1}"
	local version="$(echo "${tag}" | awk -F '-' '{print $2}')"
	local author="$(git_get_author "${tag}")"
	local email="$(git_get_email "${tag}")"
	local tagDate="$(git_get_date "${tag}")"
	local body="$(git_get_body_from_tag "${tag}")"
	cat > "${changelogFile}" << EOF
${project} (${version}) ${codename}; urgency=medium

  * Vendor stable release.
${body}

 -- ${author} <${email}>  ${tagDate}

EOF
	if [ -f "${changelogFile}.tmp" ] ; then
		cat "${changelogFile}.tmp" >> "${changelogFile}"
		/bin/rm "${changelogFile}.tmp"
	fi
}

echo "Generating chagelog for project: \`${project}'"

hasTags=0
git for-each-ref --sort='taggerdate' --format='%(tag)' refs/tags | while read tag ; do
body=$(git_get_body_from_tag "${tag}")
	if [ ! -z "${body}" ] ; then
		gen_changelog_entry "${tag}"
	fi
	hasTags=1
done

lastTagRev=""
if [ $hasTags -eq 1 ] ; then
	lastTagRev=$(git rev-list --tags --max-count=1)
fi
head=$(git rev-parse HEAD)

if [ "x${head}" != "x${lastTagRev}" ] ; then
	version=$(awk '/^VERSION *=|SUBVERSION *=|EXTRAVERSION *=/{version=version DOT $3;DOT="."}END{print version}' ./Makefile.mk.in)
	author=$(git_get_author "${head}")
	email=$(git_get_email "${head}")
	date=$(git_get_date "${head}")
	if [ -f "${changelogFile}" ] ; then
		mv -f "${changelogFile}" "${changelogFile}.tmp"
	fi
	cat > "${changelogFile}" << EOF
${project} (${version}) ${codename}; urgency=medium

  * Vendor test release.
  * commit: ${head}

 -- ${author} <${email}>  ${date}

EOF
	if [ -f "${changelogFile}.tmp" ] ; then
		cat "${changelogFile}.tmp" >> "${changelogFile}"
		/bin/rm "${changelogFile}.tmp"
	fi
fi

